package com.mobilesales.android.c2dm.parsers;

import android.content.Context;
import android.util.Log;

import com.mobilesales.android.database.OrderManager;
import com.mobilesales.android.model.orders.Order;
import com.mobilesales.android.model.orders.OrderStatus;
import com.mobilesales.android.services.OrderServiceClient;
import com.mobilesales.android.util.Settings;

public class OrderMessageParser extends MessageParserBase {

	private OrderManager manager;
	private OrderServiceClient service;	
	
	public OrderMessageParser(Context context) {
		super(context);
	}
	
	public OrderMessageParser() {
		super();
	}		
	
	@Override
	public boolean parseMessage(String method, String arg) {
		manager = new OrderManager(getContext());
		service = new OrderServiceClient(Settings.OrderService());
		try {
			this.invokeMethod(OrderMessageParser.class, method,arg);
			return true;
		}
		catch(Exception ex) {
			Log.e("MessageParser", ex.getMessage(), ex);
			return false;
		}
		finally {
			manager.Close();
		}
	}
	
	public void GetOrder(Integer id) throws Exception {
		Order item = service.GetOrder(id);
		if (item!=null) {
			if (!manager.StoreOrder(item))
				throw new Exception("Could not store order");
		}
		else {
			throw new Exception("Retrieved order is null");
		}		
	}
	
	public void DeleteOrder(Integer id) throws Exception {
		if (!manager.RemoveOrder(id))
			throw new Exception("Could not delete order");
	}		
	
	public void GetOrderStatus(Integer id) throws Exception {
		OrderStatus item = service.GetOrderStatus(id);
		if (item!=null) {
			if (!manager.StoreOrderStatus(item))
				throw new Exception("Could not store order status");
		}
		else {
			throw new Exception("Retrieved order status is null");
		}		
	}
	
	public void DeleteOrderStatus(Integer id) throws Exception {
		if (!manager.RemoveOrderStatus(id))
			throw new Exception("Could not delete order status");
	}
}
